import os
import json
import traceback
import pymysql

from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
from werkzeug.exceptions import HTTPException

app = Flask(__name__, template_folder="html")
app.secret_key = os.urandom(24)

# MySQL Configuration
db_config = {
    'host': '127.0.0.1',
    'user': 'trump',
    'passwd': 'Websecurity2024',
    'db': 'websecurity'
}

# 处理所有HTTP异常
@app.errorhandler(HTTPException)
def handle_http_exception(error):
    return render_template('error.html', error=error), error.code

# 404错误处理
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 200

# 500错误处理
@app.errorhandler(500)
def internal_error(error):
    # 获取错误的堆栈跟踪信息
    error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    
    return render_template('500.html', error=error, error_traceback=error_traceback), 200

# 处理所有未捕获的异常
@app.errorhandler(Exception)
def handle_exception(error):
    # 获取错误的堆栈跟踪信息
    error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    
    return render_template('500.html', error=error, error_traceback=error_traceback), 200

@app.route("/", methods=['GET', 'POST'])
def default():
    return render_template("login.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method=='POST':
        username = request.form['username']
        password = request.form['password']

        connection = pymysql.connect(**db_config)
        try:
            with connection.cursor(pymysql.cursors.DictCursor) as cursor:
                cursor.execute("SELECT id,username,password,role FROM user WHERE username = %s", (username,))
                user = cursor.fetchone()
        except pymysql.MySQLError as e:
            return jsonify({'error': str(e)}), 500
        finally:
            connection.close()

        if user is None:
            flash('用户名不存在', 'danger')
        else:
            userid_db = user['id']
            username_db = user['username']
            password_db = user['password']
            role_db = user['role']
            if password==password_db:
                session['user_id'] = userid_db
                session['username'] = username_db
                session['role'] = role_db

                if role_db=="admin":
                    return render_template('manage_user.html')
                else:
                    return redirect(url_for('dashboard'))
            else:
                flash('密码错误', 'danger')
                    
    return render_template('login.html')

@app.route('/dashboard')
def dashboard():
    username = session.get('username')
    if username:
        return render_template('success.html', username=username)
    else:
        return redirect(url_for('login')) 

@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))

@app.route('/admin/manage_users', methods=['GET', 'POST'])
def admin_manage_users():
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            sql = "SELECT id, username, password, role, email FROM user"
            cursor.execute(sql)
            result = cursor.fetchall()
            return jsonify(result)
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e)}), 500
    finally:
        connection.close()

@app.route('/admin/add_user', methods=['POST'])
def admin_add_user():
    data = request.get_json()
    if data is None:
        return jsonify({'error': '无效的请求数据'}), 400
    username = data.get('username')
    password = data.get('password')
    role = data.get('role')
    email = data.get('email')

    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO user (username, password, role, email) VALUES (%s, %s, %s, %s)"
            cursor.execute(sql, (username, password, role, email))
            connection.commit()
            return jsonify({'message': '用户添加成功'})
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e)}), 500
    finally:
        connection.close()

@app.route('/admin/delete_user', methods=['POST'])
def admin_delete_user():
    user_id = request.json.get('id')

    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            sql = "DELETE FROM user WHERE id = %s"
            result = cursor.execute(sql, (user_id))
            connection.commit()
            return jsonify({'message': '用户删除成功'})
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e)}), 500
    finally:
        connection.close()

# 发送电子邮件的方法
def send_email(sender_email, sender_password, recipient_email, subject, body):
    """
    :sender_email: 发送方email
    :sender_password: 发送方email的密码，注意邮件服务器可能会专门设置一个用于第三方登录发送邮件的授权密码
    :recipient_email: 接收方email
    :subject: 邮件主题
    :body: 邮件正文
    """
    # 创建一个 MIMEMultipart 对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject

    # 添加邮件正文
    msg.attach(MIMEText(body, 'plain'))

    try:
        # 设置 SMTP 服务器和端口
        smtp_server = 'smtp.163.com'  # 替换为你的 SMTP 服务器
        smtp_port = 25  # 常用端口

        # 连接到 SMTP 服务器
        server = smtplib.SMTP(smtp_server, smtp_port)
        # server.starttls()  # 启用 TLS 加密
        server.login(sender_email, sender_password)  # 登录

        # 发送邮件
        server.send_message(msg)
        print("Email sent successfully!")
    except Exception as e:
        print(f"Failed to send email: {e}")
    finally:
        server.quit()  # 关闭连接

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8001, debug=True)